import sys

import cv2
import keras
import numpy
import os

from PIL import Image
import numpy as np
from photoClassify.project.faceClasiify.config import peoples_dir_path, image_size

path = peoples_dir_path  # 要训练的人脸文件夹 每人一个 文件夹名就是人名


def loadFaceData():
    print('---数据加载路径:'+path)
    peoplesDir = os.listdir(path)
    peoplesDir.remove(".DS_Store")  # 删除mac文件夹下的隐藏文件
    peoplesDir = sorted(peoplesDir)
    peopleSize = len(peoplesDir)

    x_train = []
    y_train = []
    classNum = 0

    '''
    此方法加载出的数据会有块状集合  keras训练时shuffle=True会混洗
    浮点加归一化提高计算速度
    '''
    for peopleDir in peoplesDir:
        peoplePath = os.path.abspath(os.path.join(path, peopleDir))
        for picItem in os.listdir(peoplePath):
            picPath = os.path.abspath(os.path.join(peoplePath, picItem))
            if picPath.endswith('.jpg') | picPath.endswith('.png'):
                image = cv2.imread(picPath)
                # 调整图像大小(加载时调整或者截取时调整)  识别时也要做相同调整!
                # image = image.resize((50, 50))
                image = cv2.resize(image, image_size)
                x_train.append(numpy.asarray(image))
                y_train.append(numpy.asarray([classNum]))
        classNum = classNum + 1
    x_train = np.asarray(x_train)
    y_train = np.asarray(y_train)
    # Normalize data.
    x_train = x_train.astype('float32') / 255
    # Convert class vectors to binary class matrices.
    y_train = keras.utils.to_categorical(y_train, classNum)
    return classNum, x_train, y_train


# loadFaceData()
# 不能sys.exit(1)  因为别的类加载此类时会执行然后程序直接终止
